package cn.tedu.web.ycw.Servlet;

import cn.tedu.web.ycw.JdbcUtils;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(urlPatterns = "/goods/insert")
@MultipartConfig(
        //文件保存的位置(不要声明为当前工程中的目录；一定要存在)
        location = "D:/upload-images",
        //设置文件最大允许的字节数
        maxFileSize = 100 * 1024 * 1024,
        //设置请求最大允许的字节数,要求：maxRequestSize >= maxFileSize
        maxRequestSize = 100 * 1024 * 1024)
public class GoodsInsertServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数(文件)
        String name = req.getParameter("n");
        String price = req.getParameter("p");
        Part file = req.getPart("i");
//        String files = file.getSubmittedFileName();
//        RandomStringUtils.randomAlphanumeric(10);

//        时间戳：计算机元年到此刻的毫秒数
//        System.currentTimeMillis();

//        时间戳：计算机元年到此刻的纳秒数
//        System.nanoTime();
        String imgName =RandomStringUtils.randomAlphabetic(10) + System.nanoTime();
        //2.保存文件
        file.write("a.png");
        //3.修改数据库(insert)
        String sql = "INSERT INTO `goods`(`name`,`price`,`image`) VALUES(?,?,?)";
        JdbcUtils.modify(sql,name,price,imgName);
        System.out.println(name);
        System.out.println(price);
        //4.跳转到商品列表页面
        resp.sendRedirect("/ycw/goods-list.jsp");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
